package yf.mall.controller.api;

import com.yf.annotation.LoginUserId;
import com.yf.response.RRException;
import yf.mall.dao.*;
import yf.mall.entity.*;
import yf.mall.enums.MallActStatusEnum;
import yf.mall.enums.MallGoodsOpenSkuEnum;
import yf.mall.enums.MallGoodsSaleTypeEnum;
import com.yf.response.R;
import yf.mall.service.*;
import yf.mall.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import yf.mall.vo.ItemVo;
import yf.mall.vo.TicketVo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/api/cart")
@RestController
public class ApiCartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private PriceService priceService;

    @Autowired
    private MallOrderService mallOrderService;

    @Autowired
    private MallGoodsService goodsService;

    @Autowired
    private MallActService actService;

    @Autowired
    private LevelDao levelDao;

    @Autowired
    private LevelService levelService;

    @Autowired
    private MallSkuDao mallSkuDao;

    @Autowired
    private StoresService storesService;


    //TODO 暂时不分页
    @GetMapping("/list")
    public R info(@LoginUserId Long userId) {
        List<CartVo> cartVos = cartService.findByUserId(userId);
        List<CartVo> cartVoList = new ArrayList<>();
        //计算级别价格
        cartVos.forEach(cartVo -> {
            MallGoodsEntity goodsEntity = goodsService.get(cartVo.getGoodsId());
            MallActEntity actEntity = actService.findByGoodsIdAndstatus(cartVo.getGoodsId(), MallActStatusEnum.OPEN.getIndex());
            if (actEntity != null && actEntity.getBindGoodsId() != null){
                MallGoodsEntity mallGoodsEntity = goodsService.get(actEntity.getBindGoodsId());
                cartVo.setBindGoodsName(mallGoodsEntity.getName());
                cartVo.setBindQuantity(actEntity.getBindGoodsQuantity());
                cartVo.setFirstQuantity(actEntity.getFirstGoodsQuantity());
                MallActEntity bindAct = actService.findByGoodsIdAndstatus(actEntity.getBindGoodsId(), MallActStatusEnum.OPEN.getIndex());
                if (bindAct != null && bindAct.getLevel() != null && !bindAct.getLevel().equals("")) {
                    cartVo.setLevel(bindAct.getLevel());
                }
            }
            TicketVo ticketVo = actService.getTicketVo(goodsEntity.getId());
            //设置积分
            cartVo.setPoint(ticketVo.getPoint());
            //设置优惠券
            cartVo.setCoupon(ticketVo.getCoupon());

            //设置换购券
            if (goodsEntity.getSaleType() == MallGoodsSaleTypeEnum.VOUCHER.getIndex()) {
                if (ticketVo.getVoucher() != null && !"".equals(ticketVo.getVoucher())) {
                    cartVo.setVoucher(ticketVo.getVoucher());
                }
            }
            //设置清货券
            if (goodsEntity.getSaleType() == MallGoodsSaleTypeEnum.CLEAR.getIndex()) {
                if (ticketVo.getClear() != null && !"".equals(ticketVo.getClear())) {
                    cartVo.setClear(ticketVo.getClear());
                }
            }
            //是代理产品 获取代理价格
            if (cartVo.getGoodsSaleType().equals(MallGoodsSaleTypeEnum.AGENT.getIndex())) {
                UserEntity userEntity = userDao.get(userId);
                PriceEntity priceEntity = priceService.findByUserIdAndGoodsIdAndCode(userId, cartVo.getGoodsId(),userEntity.getTCode());
                if (priceEntity != null) {//设置代理价格
                    cartVo.setGoodsNowPrice(priceEntity.getPrice());
                }
            }
            if (cartVo.getGoodsSaleType().equals(MallGoodsSaleTypeEnum.STORES.getIndex())) {
                StoresEntity stores = this.storesService.findByUserId(userId);
                LevelEntity levelEntity = this.levelService.findByUserId(userId,goodsEntity.getAuth());
                if (stores != null || levelEntity.getLv() <= 6) {
                    cartVo.setGoodsNowPrice(goodsEntity.getShopPrice());
                }
            }
            //设置规格价格
            cartVo.setSkuNowPrice(cartVo.getSkuNowPrice());
            if (!goodsEntity.getSaleType().equals(MallGoodsSaleTypeEnum.LOTTERY.getIndex())) {
                cartVoList.add(cartVo);
            }else {
                CartEntity cartEntity = cartService.get(cartVo.getId());
                cartEntity.setSelected(false);
                cartService.update(cartEntity);
            }
        });
        return R.ok(cartVoList);
    }
    //TODO 暂时不分页

    @Autowired
    private UserDao userDao;

    @Autowired
    private LotteryRecordDao lotteryRecordDao;
 @Autowired
    private LotteryGoodsDao lotteryGoodsDao;

    /**
     * 奖品购物车集合
     * @param userId
     * @return
     */
    @GetMapping("/lotteryList")
    public R LotteryInfo(@LoginUserId Long userId,Long recordId) {
        List<CartVo> cartVos = cartService.findByUserId(userId);
        if (recordId==null){
            throw new RRException("您没有中奖");
        }
        LotteryRecordEntity recordEntity = this.lotteryRecordDao.get(recordId);
        if (recordEntity==null) {
            throw new RRException("您没有中奖");
        }
        LotteryGoodsEntity lotteryGoodsEntity = null;
        //获取奖品信息
        if (recordEntity.getGoodsId()!=null) {
            lotteryGoodsEntity = lotteryGoodsDao.get(recordEntity.getGoodsId());
        }
        if (lotteryGoodsEntity==null) {
            throw new RRException("您没有中奖");
        }
        List<CartVo> cartVoList = new ArrayList<>();
        //计算级别价格
        cartVos.forEach(cartVo -> {
            MallGoodsEntity goodsEntity = goodsService.get(cartVo.getGoodsId());
            TicketVo ticketVo = actService.getTicketVo(goodsEntity.getId());
            //设置积分
            cartVo.setPoint(ticketVo.getPoint());
            //设置优惠券
            cartVo.setCoupon(ticketVo.getCoupon());

            //设置换购券
            if (goodsEntity.getSaleType() == MallGoodsSaleTypeEnum.VOUCHER.getIndex()) {
                if (ticketVo.getVoucher() != null && !"".equals(ticketVo.getVoucher())) {
                    cartVo.setVoucher(ticketVo.getVoucher());
                }
            }
            //设置清货券
            if (goodsEntity.getSaleType() == MallGoodsSaleTypeEnum.CLEAR.getIndex()) {
                if (ticketVo.getClear() != null && !"".equals(ticketVo.getClear())) {
                    cartVo.setClear(ticketVo.getClear());
                }
            }
            //是代理产品 获取代理价格
            if (cartVo.getGoodsSaleType().equals(MallGoodsSaleTypeEnum.AGENT.getIndex())) {
                UserEntity user = userDao.get(userId);
                PriceEntity priceEntity = priceService.findByUserIdAndGoodsIdAndCode(userId, cartVo.getGoodsId(),user.getTCode());
                if (priceEntity != null) {//设置代理价格
                    cartVo.setGoodsNowPrice(priceEntity.getPrice());
                }
            }
            if (cartVo.getGoodsSaleType().equals(MallGoodsSaleTypeEnum.STORES.getIndex())) {
                StoresEntity stores = this.storesService.findByUserId(userId);
                LevelEntity levelEntity = this.levelService.findByUserId(userId,goodsEntity.getAuth());
                if (stores != null || levelEntity.getLv() <= 6) {
                    cartVo.setGoodsNowPrice(goodsEntity.getShopPrice());
                }
            }
            //设置规格价格
            cartVo.setSkuNowPrice(cartVo.getGoodsNowPrice());
            //判断是否符合奖品的相关设定
            if (goodsEntity.getSaleType().equals(MallGoodsSaleTypeEnum.LOTTERY.getIndex())&&recordEntity!=null&&recordEntity.getBandGoodsId()!=null&&goodsEntity.getId().equals(recordEntity.getBandGoodsId())) {
               cartVo.setSelected(true);
               cartVo.setQuantity(1);
               cartService.update(cartVo);
                cartVoList.add(cartVo);
            }else {
                CartEntity cartEntity = cartService.get(cartVo.getId());
                cartEntity.setSelected(false);
                cartService.update(cartEntity);
            }
        });
        return R.ok(cartVoList).putExtra("lotteryGoods",lotteryGoodsEntity);
    }



    //计算物流费
    @RequestMapping("/logFee")
    public R logFee(@LoginUserId Long userId, String province, Integer temp) {
        BigDecimal bigDecimal = BigDecimal.ZERO;
        //如果是到店自提则不计算物流费
        if (temp == null || temp == 0) {
            List<CartEntity> cartEntities = cartService.findByUserIdWithSelected(userId);
            bigDecimal = mallOrderService.computeLogFee(cartEntities, province);
        }
        return R.ok(bigDecimal);
    }


    /**
     * 修改购物车数量
     *
     * @param cartId
     * @param amount
     * @return
     */
    @PostMapping("/change")
    public R change(@LoginUserId Long userId, Long cartId, Integer amount, Boolean selected,Long bindId) {
        cartService.change(userId, cartId, amount, selected,bindId);
        return R.ok();
    }

    /**
     * 新增购物车
     *
     * @param userId
     * @param goodsId
     * @param skuName
     * @return
     */
    @PostMapping("/add")
    public R addCart(@LoginUserId Long userId, Long goodsId, String skuName, Integer quantity) {
        cartService.addCart(userId, goodsId, skuName, quantity);

        return R.ok();
    }

    /**
     * 删除购物车
     *
     * @param userId
     * @param id
     * @return
     */
    @PostMapping("/delete")
    public R deleteCart(@LoginUserId Long userId, Long id,Long bindId) {
        CartEntity cartEntity = cartService.get(id);
        //只能删除自己的
        if (cartEntity.getUserId().equals(userId)) {
            cartService.delete(id);
            if (bindId != null){
                cartService.delete(bindId);
            }
        } else {
            return R.error("非法操作!");
        }
        return R.ok();
    }

    /**
     * 清空购物车
     *
     * @param userId
     * @param
     * @return
     */
    @PostMapping("/all/delete")
    public R deleteAll(@LoginUserId Long userId) {
        cartService.deleteAll(userId);
        return R.ok();
    }


    /**
     * 全选购物车
     *
     * @param userId
     * @param id
     * @return
     */
    @PostMapping("/all/selected")
    public R chaneAllSelected(@LoginUserId Long userId, boolean selected) {
        cartService.changeAllSelected(userId, selected);
        return R.ok();
    }
}
